﻿Imports System.IO
Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Excel.Constants
Imports Microsoft.Office.Interop.Excel.XlLineStyle
Imports System.Drawing.Printing
Imports System.Drawing.Printing.PrintDocument
Imports GBDZafiro



Public Class FrmPrinter

    '' Creamos un objeto Excel
    Dim m_Excel As Excel.Application
    Dim Empresaa, nit, direccion, telefono, usuario, fecha, tListado As String
    Dim empresa As GBDZafiro.Empresa

    Private Shared addTitulo As Boolean
    Dim uso, printMatriz As Boolean
    Dim nReporte As Integer
    Dim reporte As String
    Public Shared path As String
    Public Shared dtProd As DataTable
    Private rProd As DataRow

    Private prtSettings As PrinterSettings
    Private prtDoc As PrintDocument
    Private prtFont As System.Drawing.Font
    '
    Private lineaActual As Integer

    Public Sub New(nReporte As Integer, Optional ByRef uso As Boolean = False)
        ' Llamada necesaria para el diseñador.
        InitializeComponent()
        ' Agregue cualquier inicialización después de la llamada a InitializeComponent().
        Me.nReporte = nReporte
        Me.uso = uso
        crearEmpresa()
    End Sub

    Private Sub FrmPrinter_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        prtFont = New System.Drawing.Font("Courier New", 11)
    End Sub

    Private Sub FrmPrinter_FormClosing(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If Not m_Excel Is Nothing Then

            m_Excel.Quit()

            m_Excel = Nothing

        End If
    End Sub

    Private Sub btGrafica_Click(sender As System.Object, e As System.EventArgs) Handles btGrafica.Click
        SelectModoImprimir(False)
    End Sub

    Private Sub btMatricial_Click(sender As System.Object, e As System.EventArgs) Handles btMatricial.Click
        seleccionarImpresora()
        SelectModoImprimir(True)
        'imprimir(False)
    End Sub

    Private Sub crearDirectorios(ByRef direccion As String)
        direccion += "\inventario y facturacion"
        If Not Directory.Exists(direccion) Then
            Directory.CreateDirectory(direccion)
        End If
        direccion += "\reportes"
        If Not Directory.Exists(direccion) Then
            Directory.CreateDirectory(direccion)
        End If
    End Sub

    Private Sub impGraf()
        Dim i As Integer = 8
        path = Environment.CurrentDirectory
        crearDirectorios(path)
        path += "\informe" + "-" + FormatDateTime(Now, DateFormat.LongDate)
        Dim archivo As String = path + ".xlsx"
        If My.Computer.FileSystem.FileExists(archivo) Then
            Exit Sub
        End If


        '' Creamos un objeto WorkBook
        Dim objLibroExcel As Excel.Workbook
        '' Creamos un objeto WorkSheet
        Dim objHojaExcel As Excel.Worksheet
        crearPlantilla(objLibroExcel, objHojaExcel)

        For Each rProd As DataRow In dtProd.Rows
            objHojaExcel.Cells(i, 1) = rProd("PRODUCTO")
            objHojaExcel.Cells(i, 1).HorizontalAlignment = xlLeft
            objHojaExcel.Cells(i, 2) = rProd("DESCRIPCION")
            objHojaExcel.Cells(i, 3) = rProd("REFERENCIA")
            objHojaExcel.Cells(i, 4) = rProd("UNIDAD")
            objHojaExcel.Cells(i, 5) = rProd("EXISTENCIA")
            i += 1
        Next

        Dim strRangoTotal As String = "A7:" & nombreColumna(dtProd.Columns.Count) & dtProd.Rows.Count.ToString
        '' Seleccionar todo el bloque desde A1 hasta D #de filas 
        Dim objRango As Excel.Range = objHojaExcel.Range(strRangoTotal)
        objRango.Select()
        objRango.Columns.AutoFit()

        m_Excel.Visible = True
        objHojaExcel.SaveAs(path)
        objLibroExcel.Save()
        'objLibroExcel.Close()
        objLibroExcel.PrintPreview()
    End Sub

    Private Sub crearPlantilla(ByRef objLibroExcel As Excel.Workbook, ByRef objHojaExcel As Excel.Worksheet)

        fecha = "FECHA IMPRESION: [" + FormatDateTime(Now, DateFormat.ShortDate) + "]"
        usuario = " IMPRESO POR: " + Login.usuario.nomUsuario

        '' Iniciamos una instancia a Excel
        m_Excel = New Excel.Application
        'm_Excel.Visible = True

        '' Creamos una variable para guardar la cultura actual
        Dim OldCultureInfo As System.Globalization.CultureInfo = _
            System.Threading.Thread.CurrentThread.CurrentCulture

        'Crear una cultura standard (en-US) inglés estados unidos
        System.Threading.Thread.CurrentThread.CurrentCulture = _
            New System.Globalization.CultureInfo("en-US")

        '' Creamos una instancia del Workbooks de Excel

        '' Creamos una instancia de la primera hoja de trabajo de Excel
        objLibroExcel = m_Excel.Workbooks.Add()
        objHojaExcel = objLibroExcel.Worksheets(1)
        objHojaExcel.Visible = Excel.XlSheetVisibility.xlSheetVisible

        '' Hacemos esta hoja la visible en pantalla

        '' (como seleccionamos la primera esto no es necesario

        '' si seleccionamos una diferente a la primera si lo

        '' necesitaríamos, esto lo hacemos como forma de mostrar como

        ''cambiar de entre hojas en un documento Excel).
        objHojaExcel.Activate()

        '' Crear el encabezado de nuestro informe
        objHojaExcel.Range("A1:E1").Merge()
        objHojaExcel.Range("A1:E1").Value = empresa.RAZON_SOCIAL
        objHojaExcel.Range("A1:E1").Font.Bold = True
        objHojaExcel.Range("A1:E1").Font.Size = 15
        objHojaExcel.Range("A1:E1").HorizontalAlignment = xlCenter

        '' Crear el subencabezado de nuestro informe
        objHojaExcel.Range("A2:E2").Merge()
        objHojaExcel.Range("A2:E2").Value = "Nit: " + empresa.NIT
        objHojaExcel.Range("A2:E2").Font.Italic = True
        objHojaExcel.Range("A2:E2").Font.Bold = True
        objHojaExcel.Range("A2:E2").Font.Size = 13
        objHojaExcel.Range("A2:E2").HorizontalAlignment = xlCenter

        '' Crear el subencabezado de nuestro informe
        objHojaExcel.Range("A3:E3").Merge()
        objHojaExcel.Range("A3:E3").Value = "Dirección: " + empresa.DIRECCION + " " + _
            "Telefono: " + empresa.TELEFONO
        objHojaExcel.Range("A3:E3").Font.Italic = True
        objHojaExcel.Range("A3:E3").Font.Bold = True
        objHojaExcel.Range("A3:E3").Font.Size = 13
        objHojaExcel.Range("A3:E3").HorizontalAlignment = xlCenter

        '' Crear el subencabezado de nuestro informe
        objHojaExcel.Range("A4:E4").Merge()
        objHojaExcel.Range("A4:E4").Value = reporte
        objHojaExcel.Range("A4:E4").Font.Italic = True
        objHojaExcel.Range("A4:E4").Font.Size = 13
        objHojaExcel.Range("A4:E4").HorizontalAlignment = xlCenter

        '' Crear el subencabezado de nuestro informe
        objHojaExcel.Range("A5:E5").Merge()
        objHojaExcel.Range("A5:E5").Value = fecha + " " + usuario
        objHojaExcel.Range("A5:E5").Font.Italic = True
        objHojaExcel.Range("A5:E5").Font.Size = 13
        objHojaExcel.Range("A5:E5").HorizontalAlignment = xlCenter

        Dim objCelda As Excel.Range = objHojaExcel.Range("A7", Type.Missing)
        objCelda.Value = "CODIGO"
        objCelda.HorizontalAlignment = xlLeft

        objCelda = objHojaExcel.Range("B7", Type.Missing)
        objCelda.Value = "DESCRIPCION"

        objCelda = objHojaExcel.Range("C7", Type.Missing)
        objCelda.Value = "REFERENCIA"

        objCelda = objHojaExcel.Range("D7", Type.Missing)
        objCelda.Value = "UNIDAD"

        objCelda = objHojaExcel.Range("E7", Type.Missing)
        objCelda.Value = "EXISTENCIA"

        'Border 
        objHojaExcel.Range("A7", "E7"). _
            Borders(Excel.XlBordersIndex.xlEdgeTop).LineStyle = xlDash
        objHojaExcel.Range("A8", "E8"). _
           Borders(Excel.XlBordersIndex.xlEdgeTop).LineStyle = xlDash
    End Sub

    Public Function nombreColumna(ByVal numero As Integer) As String
        Dim columna(256) As String

        columna(1) = "A"
        columna(2) = "B"
        columna(3) = "C"
        columna(4) = "D"
        columna(5) = "E"
        columna(6) = "F"
        columna(7) = "G"
        columna(8) = "H"
        columna(9) = "I"
        columna(10) = "J"
        columna(11) = "K"
        columna(12) = "L"
        columna(13) = "M"
        columna(14) = "N"
        columna(15) = "O"
        columna(16) = "P"
        columna(17) = "Q"
        columna(18) = "R"
        columna(19) = "S"
        columna(20) = "T"
        columna(21) = "U"
        columna(22) = "V"
        columna(23) = "W"
        columna(24) = "X"
        columna(25) = "Y"
        columna(26) = "Z"
        columna(27) = "AA"
        columna(28) = "AB"
        columna(29) = "AC"
        columna(30) = "AD"
        columna(31) = "AE"
        columna(32) = "AF"
        columna(33) = "AG"
        columna(34) = "AH"
        columna(35) = "AI"
        columna(36) = "AJ"
        columna(37) = "AK"
        columna(38) = "AL"
        columna(39) = "AM"
        columna(40) = "AN"
        columna(41) = "AO"
        columna(42) = "AP"
        columna(43) = "AQ"
        columna(44) = "AR"
        columna(45) = "AS"
        columna(46) = "AT"
        columna(47) = "AU"
        columna(48) = "AV"
        columna(49) = "AW"
        columna(50) = "AX"
        columna(51) = "AY"
        columna(52) = "AZ"
        columna(53) = "BA"
        columna(54) = "BB"
        columna(55) = "BC"
        columna(56) = "BD"
        columna(57) = "BE"
        columna(58) = "BF"
        columna(59) = "BG"
        columna(60) = "BH"
        columna(61) = "BI"
        columna(62) = "BJ"
        columna(63) = "BK"
        columna(64) = "BL"
        columna(65) = "BM"
        columna(66) = "BN"
        columna(67) = "BO"
        columna(68) = "BP"
        columna(69) = "BQ"
        columna(70) = "BR"
        columna(71) = "BS"
        columna(72) = "BT"
        columna(73) = "BU"
        columna(74) = "BV"
        columna(75) = "BW"
        columna(76) = "BX"
        columna(77) = "BY"
        columna(78) = "BZ"
        columna(79) = "CA"
        columna(80) = "CB"
        columna(81) = "CC"
        columna(82) = "CD"
        columna(83) = "CE"
        columna(84) = "CF"
        columna(85) = "CG"
        columna(86) = "CH"
        columna(87) = "CI"
        columna(88) = "CJ"
        columna(89) = "CK"
        columna(90) = "CL"
        columna(91) = "CM"
        columna(92) = "CN"
        columna(93) = "CO"
        columna(94) = "CP"
        columna(95) = "CQ"
        columna(96) = "CR"
        columna(97) = "CS"
        columna(98) = "CT"
        columna(99) = "CU"
        columna(100) = "CV"
        columna(101) = "CW"
        columna(102) = "CX"
        columna(103) = "CY"
        columna(104) = "CZ"
        columna(105) = "DA"
        columna(106) = "DB"
        columna(107) = "DC"
        columna(108) = "DD"
        columna(109) = "DE"
        columna(110) = "DF"
        columna(111) = "DG"
        columna(112) = "DH"
        columna(113) = "DI"
        columna(114) = "DJ"
        columna(115) = "DK"
        columna(116) = "DL"
        columna(117) = "DM"
        columna(118) = "DN"
        columna(119) = "DO"
        columna(120) = "DP"
        columna(121) = "DQ"
        columna(122) = "DR"
        columna(123) = "DS"
        columna(124) = "DT"
        columna(125) = "DU"
        columna(126) = "DV"
        columna(127) = "DW"
        columna(128) = "DX"
        columna(129) = "DY"
        columna(130) = "DZ"
        columna(131) = "EA"
        columna(132) = "EB"
        columna(133) = "EC"
        columna(134) = "ED"
        columna(135) = "EE"
        columna(136) = "EF"
        columna(137) = "EG"
        columna(138) = "EH"
        columna(139) = "EI"
        columna(140) = "EJ"
        columna(141) = "EK"
        columna(142) = "EL"
        columna(143) = "EM"
        columna(144) = "EN"
        columna(145) = "EO"
        columna(146) = "EP"
        columna(147) = "EQ"
        columna(148) = "ER"
        columna(149) = "ES"
        columna(150) = "ET"
        columna(151) = "EU"
        columna(152) = "EV"
        columna(153) = "EW"
        columna(154) = "EX"
        columna(155) = "EY"
        columna(156) = "EZ"
        columna(157) = "FA"
        columna(158) = "FB"
        columna(159) = "FC"
        columna(160) = "FD"
        columna(161) = "FE"
        columna(162) = "FF"
        columna(163) = "FG"
        columna(164) = "FH"
        columna(165) = "FI"
        columna(166) = "FJ"
        columna(167) = "FK"
        columna(168) = "FL"
        columna(169) = "FM"
        columna(170) = "FN"
        columna(171) = "FO"
        columna(172) = "FP"
        columna(173) = "FQ"
        columna(174) = "FR"
        columna(175) = "FS"
        columna(176) = "FT"
        columna(177) = "FU"
        columna(178) = "FV"
        columna(179) = "FW"
        columna(180) = "FX"
        columna(181) = "FY"
        columna(182) = "FZ"
        columna(183) = "GA"
        columna(184) = "GB"
        columna(185) = "GC"
        columna(186) = "GD"
        columna(187) = "GE"
        columna(188) = "GF"
        columna(189) = "GG"
        columna(190) = "GH"
        columna(191) = "GI"
        columna(192) = "GJ"
        columna(193) = "GK"
        columna(194) = "GL"
        columna(195) = "GM"
        columna(196) = "GN"
        columna(197) = "GO"
        columna(198) = "GP"
        columna(199) = "GQ"
        columna(200) = "GR"
        columna(201) = "GS"
        columna(202) = "GT"
        columna(203) = "GU"
        columna(204) = "GV"
        columna(205) = "GW"
        columna(206) = "GX"
        columna(207) = "GY"
        columna(208) = "GZ"
        columna(209) = "HA"
        columna(210) = "HB"
        columna(211) = "HC"
        columna(212) = "HD"
        columna(213) = "HE"
        columna(214) = "HF"
        columna(215) = "HG"
        columna(216) = "HH"
        columna(217) = "HI"
        columna(218) = "HJ"
        columna(219) = "HK"
        columna(220) = "HL"
        columna(221) = "HM"
        columna(222) = "HN"
        columna(223) = "HO"
        columna(224) = "HP"
        columna(225) = "HQ"
        columna(226) = "HR"
        columna(227) = "HS"
        columna(228) = "HT"
        columna(229) = "HU"
        columna(230) = "HV"
        columna(231) = "HW"
        columna(232) = "HX"
        columna(233) = "HY"
        columna(234) = "HZ"
        columna(235) = "IA"
        columna(236) = "IB"
        columna(237) = "IC"
        columna(238) = "ID"
        columna(239) = "IE"
        columna(240) = "IF"
        columna(241) = "IG"
        columna(242) = "IH"
        columna(243) = "II"
        columna(244) = "IJ"
        columna(245) = "IK"
        columna(246) = "IL"
        columna(247) = "IM"
        columna(248) = "IN"
        columna(249) = "IO"
        columna(250) = "IP"
        columna(251) = "IQ"
        columna(252) = "IR"
        columna(253) = "IS"
        columna(254) = "IT"
        columna(255) = "IU"
        columna(256) = "IV"

        Return columna(numero)
    End Function

    Private Sub crearEmpresa()
        Dim dtEmp As DataTable = GBDZafiro.Empresa.ConsxPrimEmp()
        Me.empresa = New GBDZafiro.Empresa
        For Each rEmp As DataRow In dtEmp.Rows
            Me.empresa.RAZON_SOCIAL = rEmp("RAZON_SOCIAL")
            Me.empresa.NIT = rEmp("NIT") + "-" + rEmp("DIG_VER")
            Me.empresa.DIRECCION = rEmp("DIRECCION")
            Me.empresa.TELEFONO = rEmp("TELEFONO")
        Next
    End Sub

    Private Sub imprimir(ByRef esPreview As Boolean)
        ' imprimir o mostrar el PrintPreview

        If prtSettings Is Nothing Then
            prtSettings = New PrinterSettings
        End If

        'If chkSelAntes.Checked Then
        '    If seleccionarImpresora() = False Then Return
        'End If

        If prtDoc Is Nothing Then
            prtDoc = New System.Drawing.Printing.PrintDocument
            ' = vbPRPSA4Small 'New Printing.PaperSize("Carta", 2550, 3300)
            AddHandler prtDoc.PrintPage, AddressOf prt_PrintPage
        End If

        ' la línea actual
        lineaActual = 0

        ' la configuración a usar en la impresión
        prtDoc.PrinterSettings = prtSettings

        If esPreview Then
            printMatriz = False
            Dim prtPrev As New PrintPreviewDialog
            prtPrev.Document = prtDoc

            prtPrev.Text = "Previsualizar documento"
            prtPrev.ShowDialog()
        Else
            'printMatriz = True
            prtDoc.Print()
        End If
    End Sub

    Private Sub SelectModoImprimir(imp As Boolean)
        Select Case nReporte
            Case 0
                If uso Then
                    dtProd = GBDZafiro.Producto.ConsInvProdEnUso()
                Else
                    dtProd = GBDZafiro.Producto.ConsInvProd()
                End If

                Me.reporte = "LISTADO GENERAL DE EXISTENCIAS"
                addTitulo = True
                If Not imp Then
                    Dim frmInvProd As New FrmRptInvProd(dtProd)
                    frmInvProd.ShowDialog()
                Else
                    Me.imprimir(False)
                End If
                
            Case 1

            Case 2

        End Select

        Me.Close()
    End Sub

    Private Function seleccionarImpresora() As Boolean
        Dim prtDialog As New PrintDialog
        If prtSettings Is Nothing Then
            prtSettings = New PrinterSettings
        End If

        With prtDialog
            .AllowPrintToFile = False
            .AllowSelection = False
            .AllowSomePages = True
            prtSettings.MinimumPage = 1
            prtSettings.MaximumPage = 99
            prtSettings.FromPage = 1
            prtSettings.ToPage = 99
            '
            .PrintToFile = False
            .ShowHelp = False
            .ShowNetwork = True
            .PrinterSettings = prtSettings

            If .ShowDialog() = DialogResult.OK Then
                prtSettings = .PrinterSettings
            Else
                Return False
            End If

        End With

        Return True
    End Function
    '
    ' El evento usado mientras se imprime el documento
    Private Sub prt_PrintPage(ByVal sender As Object, _
                              ByVal e As System.Drawing.Printing.PrintPageEventArgs)
        ' Este evento se produce cada vez que se va a imprimir una página
        Dim lineHeight As Single
        Dim yPos As Single = e.MarginBounds.Top
        Dim leftMargin As Single = e.MarginBounds.Left
        Dim printFont As System.Drawing.Font
        Dim sb As System.Text.StringBuilder
        Dim lvi As ListViewItem
        '
        Dim printProd As New printProducto(Me.empresa)
        'Asignar dtProd
        printProd.ToColumnHeaders(dtProd)
        ' Asignar el tipo de letra
        printFont = prtFont
        lineHeight = printFont.GetHeight(e.Graphics)
        '
        If addTitulo Then
            Dim fontTitulo As New Font("Arial", 20, FontStyle.Bold)
            yPos = printProd.TituloImpresion(e, fontTitulo, yPos)
            addTitulo = False
            If printMatriz Then '''' aqui se imprime linea a linea
                prtDoc.Print()
                e.Graphics.Clear(System.Drawing.Color.White)
            End If
        End If
       
        yPos = printProd.CabeceraImpresion(e, printFont, yPos)
        If printMatriz Then '''' aqui se imprime linea a linea
            prtDoc.Print()
            e.Graphics.Clear(System.Drawing.Color.White)
        End If

        ' imprimir cada una de las líneas de esta página
        Do
            yPos += lineHeight
            e.Graphics.DrawString(printProd.LineaImpresión(lineaActual), _
                                  printFont, Brushes.Black, 20, yPos)

            If printMatriz Then '''' aqui se imprime linea a linea
                prtDoc.Print()
                e.Graphics.Clear(System.Drawing.Color.White)
            End If

            lineaActual += 1
        Loop Until yPos >= e.MarginBounds.Bottom - 40 OrElse lineaActual >= dtProd.Rows.Count ''''' menos dos renglones
        '
        If lineaActual < dtProd.Rows.Count Then
            e.HasMorePages = True
        Else
            e.HasMorePages = False
        End If
    End Sub
    '
End Class